<?php
class memberActions extends sfActions {

  public function executeAddMember(sfWebRequest $request) {
    if ($request->getParameter('did')) {
      $member = USERTable::getInstance()->find($request->getParameter('did'));
      $this->forward404Unless($member instanceof USER);
      $member->setStatus(Constants::STATUS_INACTIVE);
      $member->save();
      $this->redirect('@member_list');
    }

    if ($this->getUser()->hasCredential(Constants::USER_GROUP_SUPER_ADMIN)) {
      $this->getUser()->getAttributeHolder()->remove(Constants::SESSION_MERCHANT_ID);
    }

    $this->form = new MemberForm();
    $this->member = null;
    $errorCollector = array();

    if ($request->hasParameter('id')) {
      $member = USERTable::getInstance()->find($request->getParameter('id'));
      $this->forward404Unless($member instanceof USER);
      $this->isEdit = true;
      $this->form->populateData($member);
      $this->member = $member;
    }

    try {
      if ($request->isMethod('post')) {
        $formData = $request->getParameter(MemberForm::FORM_NAME);
        $this->form->bind($formData);

        if ($this->form->isValid()) {
          $member->setStatus($formData[MemberForm::FIELD_STATUS]);
          $member->save();
          $this->redirect('@member_edit?id='.$member->getId().'&success=1');
        }
      }
    } catch (Exception $e) {
      $errorCollector[] = LangUtil::getText('error_save_failed');
    }

    $this->errorCollector = $errorCollector;

    try {
      $sortBy = $request->hasParameter(sfConfig::get('app_sort_parameter_name')) ? $request->getParameter(sfConfig::get('app_sort_parameter_name')) : MemberForm::SORT_FIRST_NAME;
      $pager = new sfDoctrinePager('USER', sfConfig::get('app_list_records_per_page'));
      $pager->setQuery(Doctrine_Query::create()->from('USER u')->where('u.USER_GROUP_ID = ?', Constants::USER_GROUP_CUSTOMER)->orderBy('u.' . $sortBy));
      $pager->setPage($request->getParameter(sfConfig::get('app_paginator_parameter_name'), 1));
      $pager->init();
      $this->pager = $pager;
    } catch (Exception $e) {
      $this->forward404();
    }
  }
}